#!/usr/bin/env zsh
#
# These options are intended to be user-customizable if needed; you can
# override them by exporting them from your ~/.zshrc. See README for more
# details.

FZF_BIN_PATH=${FZF_BIN_PATH:="fzf"}
FZFZ_EXCLUDE_PATTERN=${FZFZ_EXCLUDE_PATTERN:="\/.git"}
FZFZ_EXTRA_OPTS=${FZFZ_EXTRA_OPTS:=""}
FZFZ_UNIQUIFIER=${FZFZ_UNIQUIFIER:="awk '!seen[\$0]++' 2>&1"}
FZFZ_SUBDIR_LIMIT=${FZFZ_SUBDIR_LIMIT:=50}

if ! (( ${+FZFZ_PREVIEW_COMMAND} )); then
    command -v exa >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        FZFZ_PREVIEW_COMMAND='exa --level 2 --tree --color=always --group-directories-first {}'
    else
        command -v tree >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            FZFZ_PREVIEW_COMMAND='tree -C -L 2 -x --noreport --dirsfirst {}'
        else
            FZFZ_PREVIEW_COMMAND='ls -1 -R {}'
        fi
    fi
fi

# *****

SCRIPT_PATH="${0:A:h}"

if [[ $OSTYPE == darwin* && -z $(whence tac) ]]; then
    REVERSER='tail -r'
else
    REVERSER='tac'
fi

if type fd &>/dev/null; then
    FIND_PREFIX="fd --color=never --hidden . "
    FIND_POSTFIX=" --type directory"
    FIND_REMOVE_SURPLUS="cat"
else
    FIND_PREFIX="find "
    FIND_POSTFIX=" -type d"
    # find includes the current directory, so we remove the first line from
    # the output.
    FIND_REMOVE_SURPLUS="tail -n +2"
fi

if (($+FZFZ_EXCLUDE_PATTERN)); then
    if type gegrep &>/dev/null; then
        EXCLUDER="gegrep -v '$FZFZ_EXCLUDE_PATTERN'"
    else
        EXCLUDER="egrep -v '$FZFZ_EXCLUDE_PATTERN'"
    fi
else
    EXCLUDER="cat"
fi

# EXCLUDER is applied directly only to searches that need it (i.e. not
# `z`). That improvements performance, and makes sure that the
# FZFZ_SUBDIR_LIMIT is applied on the post-excluded list.

if (($+FZFZ_EXTRA_DIRS)); then
    EXTRA_DIRS="{ $FIND_PREFIX $FZFZ_EXTRA_DIRS $FIND_POSTFIX && $FIND_PID=${!} | ($EXCLUDER; kill -9 $FIND_PID) } 2> /dev/null"
else
    EXTRA_DIRS="{ true }"
fi

if (($FZFZ_SUBDIR_LIMIT == 0)); then
    SUBDIRS="{ true }"
else
    SUBDIRS="{ $FIND_PREFIX '$PWD' $FIND_POSTFIX | $EXCLUDER | head -n $(($FZFZ_SUBDIR_LIMIT+1)) | $FIND_REMOVE_SURPLUS }"
fi

RECENT_DIRS="{ $SCRIPT_PATH/recentdirs.sh }"
RECENTLY_USED_DIRS="{ $RECENT_DIRS | $REVERSER | sed 's/^[[:digit:].]*[[:space:]]*//' }"

FZF_COMMAND="${FZF_BIN_PATH} --height ${FZF_TMUX_HEIGHT:-40%} ${FZFZ_EXTRA_OPTS} --no-sort --tiebreak=end,index -m --preview='$FZFZ_PREVIEW_COMMAND | head -\$LINES'"

COMMAND="{ $RECENTLY_USED_DIRS ; $SUBDIRS ; $EXTRA_DIRS; } | $FZFZ_UNIQUIFIER | $FZF_COMMAND"
eval $COMMAND
